package com.cgl.controller;

import com.cgl.pojo.Result;
import com.cgl.until.PropertiesRead;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileUploadController {
    @PostMapping("/image")
    public Result imageUpload(@RequestParam("file") MultipartFile file) throws IOException {
        // 判断文件是否为空
        if (file.isEmpty()){
            return Result.error("文件为空");
        }

        // 获取文件名
        String originalName = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + "." + getFileExtension(originalName);

        // 读取图片并压缩
        BufferedImage originalImage = ImageIO.read(file.getInputStream());
        if (originalImage == null) {
            return Result.error("无法读取图片");
        }

        // 压缩图片（缩小到四分之一）
        BufferedImage compressedImage = compressImage(originalImage);

        // 保存压缩后的图片
        String filePath = PropertiesRead.read("IMAGE_PATH") + fileName;
        File dest = new File(filePath);
        ImageIO.write(compressedImage, getFileExtension(originalName), dest);

        return Result.success(fileName);
    }

    @PostMapping("/articleimage")
    public HashMap<String,Object> articleImageUpload(@RequestParam("file") MultipartFile file) throws IOException {
        // 判断文件是否为空
        if (file.isEmpty()){
            HashMap<String,Object> result=new HashMap<>();
            result.put("errno",1);
            result.put("msg","文件为空");
            return result;
        }

        // 获取文件名
        String originalName = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + "." + getFileExtension(originalName);

        // 读取图片并压缩
        BufferedImage originalImage = ImageIO.read(file.getInputStream());
        if (originalImage == null) {
            HashMap<String,Object> result=new HashMap<>();
            result.put("errno",1);
            result.put("msg","无法读取图片");
            return result;
        }

        // 压缩图片（缩小到四分之一）
        BufferedImage compressedImage = compressImage(originalImage);

        // 保存压缩后的图片
        String filePath = PropertiesRead.read("IMAGE_PATH") + fileName;
        File dest = new File(filePath);
        ImageIO.write(compressedImage, getFileExtension(originalName), dest);

        String url=PropertiesRead.read("FrontEndImage")+fileName;

        HashMap<String,String> data=new HashMap<>();
        data.put("url",url);

        HashMap<String,Object> result=new HashMap<>();
        result.put("errno",0);
        result.put("data",data);

        /**
         * 这里是返回成功，为了兼容wangEditor的API
         */
        return result;
    }

    // 获取文件扩展名
    private String getFileExtension(String fileName) {
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            return "";
        }
    }

    // 压缩图片（缩小到四分之一）
    private BufferedImage compressImage(BufferedImage originalImage) {
        int width = originalImage.getWidth() / 2;
        int height = originalImage.getHeight() / 2;

        // 创建一个新的 BufferedImage 对象来存储压缩后的图片
        BufferedImage compressedImage = new BufferedImage(width, height, originalImage.getType());
        Graphics2D g2d = compressedImage.createGraphics();
        g2d.drawImage(originalImage, 0, 0, width, height, null);
        g2d.dispose();

        return compressedImage;
    }
}
